package com.leha.forum.lehare.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leha.forum.lehare.entity.LevelPermission;
import com.leha.forum.lehare.entity.Permission;
import com.leha.forum.lehare.service.LevelPermissionService;
import com.leha.forum.lehare.mapper.LevelPermissionMapper;
import com.leha.forum.lehare.service.PermissionService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
* @author Administrator
* @description 针对表【level_permission】的数据库操作Service实现
* @createDate 2025-04-28 18:08:48
*/
@Service
public class LevelPermissionServiceImpl extends ServiceImpl<LevelPermissionMapper, LevelPermission>
    implements LevelPermissionService{
    @Resource
    private PermissionService permissionService;

    @Override
    public boolean bindLevelPermission(Integer levelId, Integer permissionId) {
        List<Permission> existingPermissions = getLevelPermissions(levelId);

        // 判断是否已经绑定过
        if (existingPermissions.stream().filter(it -> it.getPermissionId().equals(permissionId)).toList().size() > 0) {
            // 已经存在此权限 无需绑定
            return true;
        }

        return save(new LevelPermission(null, levelId, permissionId));
    }

    @Override
    public boolean unbindLevelPermission(Integer levelId, Integer permissionId) {
        return remove(new QueryWrapper<LevelPermission>().eq("level_id", levelId).eq("permission_id", permissionId));
    }

    @Override
    public List<Permission> getLevelPermissions(Integer levelId) {
        // 获取所有关联对象
        List<LevelPermission> relations = list(new QueryWrapper<LevelPermission>().eq("level_id", levelId));

        // 转换成实际的权限对象
        return relations.stream().map(e -> permissionService.getById(e.getPermissionId())).toList();
    }
}




